package no.ffi.gismoidm.pubsub;

import java.net.InetAddress;
import java.util.ArrayList;
import java.util.StringTokenizer;
import no.ffi.gismoidm.idp.Config;
import no.ffi.tpm.crypto.CryptoOperations;

/**
 * This class reads neighbor information from the config file and
 * establishes connections with them. It also reconnects when
 * necessary
 * @author anders
 */
public class ConnectionController {
    
    class Neighbor {
        InetAddress ipaddress;
        int port;
        String mrID;
    }
    
    ArrayList<Neighbor> connectionList;

    public ConnectionController() {
        buildConnectionList();
    }
    
    private void buildConnectionList() {
        try {
            connectionList = new ArrayList();
            int c = 1;
            String n;
            while (c<100) {
                if (c<10) n = "MESSAGEROUTER_NEIGHBOR_0" + c;
                else n = "MESSAGEROUTER_NEIGHBOR_" + c;
                String nv = Config.getProperty(n);
                if (nv == null) break;
                StringTokenizer st = new StringTokenizer(nv,",");
                Neighbor nb = new Neighbor();
                nb.ipaddress = InetAddress.getByName(st.nextToken());
                nb.port = Integer.parseInt(st.nextToken());
                nb.mrID = st.nextToken();
                connectionList.add(nb);
                System.out.println("Connecting to neighbor: " + nv);
                new Authenticator(nb.ipaddress,nb.port,nb.mrID);
                c++;
            }
            if (c>1) {  // At least one neighbor, start thread for
                        //aggsubannouncements
                
            }
        } catch (Exception e) { e.printStackTrace(); }
    }
    
    
}
